import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @param sum int整型 
     * @return bool布尔型
     */
    public boolean hasPathSum (TreeNode root, int sum) {
        // write code here
        // 递归
        /*
        if (root == null) {
            return false;
        }


        if (root.left == null && root.right == null) {
            return sum == root.val;
        }

        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
        */

        // dfs
        if (root == null) 
            return false;

        Stack<TreeNode> s1 = new Stack<>();
        Stack<Integer> s2 = new Stack<>();
        s1.push(root);
        s2.push(root.val);

        while (!s1.isEmpty()) {
            TreeNode node = s1.pop();
            int num = s2.pop();

            if (node.left == null && node.right == null && num == sum) 
                return true;

            if (node.left != null) {
                s1.push(node.left);
                s2.push(num + node.left.val);
            }
            if (node.right != null) {
                s1.push(node.right);
                s2.push(num + node.right.val);
            }
        }
        return false;
    }
}